package mynet

import (
	"fmt"
	"net"
	"sync"
)

type Server struct {
	msgHandler     IMsgHandler
	clientManager  IConnectionManager
	listener       net.Listener
	ManagerRoom    IRoomManager
	OnlineUser     map[string]IConnection
	OnlineUserLock sync.Mutex
}

func (this *Server) start() {
	go this.msgHandler.StartWorkPool()
	id := 0
	for {
		client, err := this.listener.Accept()
		if err != nil {
			fmt.Println(err)
			continue
		}
		clientConn := GetNewConnection(id, client, this)
		this.clientManager.Add(clientConn)
		go clientConn.Start()
		id++
	}
}

func (this *Server) Service() {
	this.start()
}

func (this *Server) Stop() {}

func (this *Server) AddRouter(msgId int32, router IRouter) {
	this.msgHandler.AddRouter(msgId, router)
}

func GetServer(ip string, port int) *Server {
	listen, err := net.Listen("tcp", fmt.Sprintf("%s:%d", ip, port))
	if err != nil {
		panic(fmt.Sprintf("Server start error:%s", err))
	}
	msgHandler := GetNewMsgHandler(4)
	return &Server{
		listener:      listen,
		msgHandler:    msgHandler,
		clientManager: GetNewConManager(),
		ManagerRoom:   GetNewRoomManager(),
		OnlineUser:    make(map[string]IConnection),
	}
}
